package com.springboot_blog.controller;

import com.springboot_blog.common.Result;
import com.springboot_blog.dto.UserQueryDTO;
import com.springboot_blog.dto.UserUpdateDTO;
import com.springboot_blog.enums.ErrorCodeEnum;
import com.springboot_blog.exception.CustomException;
import com.springboot_blog.service.UserService;
import com.springboot_blog.vo.PageResult;
import com.springboot_blog.vo.UserListVO;
import com.springboot_blog.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {

    @Resource
    private UserService userService;


    @GetMapping
    @Operation(summary = "分页查询用户列表", description = "根据条件分页查询用户列表")
    public Result<PageResult<UserListVO>> getUserList(@Valid   UserQueryDTO queryDTO) {
        PageResult<UserListVO> userList = userService.getUserList(queryDTO);
        return Result.success("查询成功！", userList);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public Result<UserVO> getUserById(@Parameter(description = "用户ID") @PathVariable Long id) {
        UserVO userVO = userService.getUserById(id);
        return Result.success(userVO);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用户信息", description = "根据用户ID更新用户详细信息")
    public Result<Void> updateUser(@Parameter(description = "用户ID") @PathVariable Long id,
                                   @Valid @RequestBody UserUpdateDTO userUpdateDTO) {
        boolean flag = userService.updateUser(id, userUpdateDTO);

        if (flag) return Result.success("更新用户信息成功", null);
        else throw new CustomException(ErrorCodeEnum.SYSTEM_ERROR);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "逻辑删除用户")
    public Result<Void> deleteUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        boolean flag = userService.deleteUser(id);

        if (flag){
            return Result.success("删除用户成功！",null);
        }else {
            throw new CustomException(ErrorCodeEnum.SYSTEM_ERROR);
        }
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除用户", description = "批量逻辑删除用户")
    public Result<Void> deleteUsers(@RequestParam("ids") List<Long> ids) {
        boolean flag = userService.batchDeleteUsers(ids);

        if (flag){
            return Result.success("批量删除用户成功！",null);
        }else {
            throw new CustomException(ErrorCodeEnum.SYSTEM_ERROR);
        }
    }

}
